const editor = document.getElementById('markdown-editor');
const preview = document.getElementById('preview');
const lineNumbers = document.getElementById('line-numbers');
let characterName = [
    "胖虎:",
    "小夫:",
    "静香:",
    "大雄:"
];

editor.addEventListener('input', () => {
    const markdownText = editor.value;
    const htmlContent = markdownToHtml(markdownText);
    preview.innerHTML = htmlContent;
    updateLineNumbers();
});

editor.addEventListener('scroll', () => {
    lineNumbers.scrollTop = editor.scrollTop;
});

// 策略接口
class MarkdownStrategy {
    match(line) {
        throw new Error("This method should be overridden!");
    }
    parse(line) {
        throw new Error("This method should be overridden!");
    }
}

// 具体策略类
class CharacterStrategy extends MarkdownStrategy {
    constructor(index) {
        super();
        this.index = index;
    }
    match(line) {
        return line.startsWith(`#${this.index} `);
    }
    parse(line) {
        return `${characterName[this.index - 1]}${line.slice(3)}<br>`;
    }
}

class HeaderStrategy extends MarkdownStrategy {
    constructor(level) {
        super();
        this.level = level;
    }
    match(line) {
        return line.startsWith('#'.repeat(this.level) + ' ');
    }
    parse(line) {
        return `<h${this.level}>${line.slice(this.level + 1)}</h${this.level}>`;
    }
}

class DefaultStrategy extends MarkdownStrategy {
    match(line) {
        return true;
    }
    parse(line) {
        return line.trim() ? `${line}<br>` : '<br>';
    }
}

// 策略集合
const strategies = [
    new CharacterStrategy(1),
    new CharacterStrategy(2),
    new CharacterStrategy(3),
    new CharacterStrategy(4),
    new HeaderStrategy(6),
    new HeaderStrategy(5),
    new HeaderStrategy(4),
    new HeaderStrategy(3),
    new HeaderStrategy(2),
    new HeaderStrategy(1),
    new DefaultStrategy()
];

function markdownToHtml(markdown) {
    return markdown
        .split('\n')
        .map(line => {
            for (const strategy of strategies) {
                if (strategy.match(line)) {
                    return strategy.parse(line);
                }
            }
        })
        .join('');
}

function updateLineNumbers() {
    const lines = editor.value.split('\n').length;
    lineNumbers.innerHTML = Array.from({ length: lines }, (_, i) => i + 1).join('<br>');
}

// 初始化行号
updateLineNumbers();